import time
from datetime import datetime
from typing import Any

from celery import shared_task
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from src.config.settings import settings
from src.models.export_task import ExportTask, TaskStatus

# from celery_app import celery_app


# 创建数据库引擎
db_engine = create_engine(settings.database_url)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=db_engine)

# 创建表结构（如果不存在）
# try:
#     Base.metadata.create_all(bind=db_engine)
# except Exception as e:
#     print(f"Database table creation failed: {e}")


def get_db_session() -> Any:
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@shared_task(bind=True)  # type: ignore
def export_data(self: Any, task_id: str) -> bool | Exception:
    session = next(get_db_session())
    try:
        # 获取导出任务
        task = session.query(ExportTask).filter(ExportTask.task_id == task_id).first()
        if not task:
            raise ValueError(f"任务ID {task_id} 不存在")

        task.status = TaskStatus.PROCESSING
        task.started_at = datetime.utcnow()
        session.commit()

        # 模拟数据导出任务
        task.total_records = 100  # 指定模拟总记录数
        for i in range(task.total_records):
            # 模拟处理记录
            task.processed_records += 1
            # 模拟处理时间
            time.sleep(0.1)  # 每条记录处理100ms

            # 保存进度到数据库
            if i % 10 == 0:
                session.commit()

        # 更新任务结果
        task.status = TaskStatus.SUCCESS
        task.finished_at = datetime.utcnow()
        task.result_file_path = "./data.csv"  # 生成的文件路径
    except Exception as e:
        task.status = TaskStatus.FAILED
        task.error_message = str(e)
        session.commit()
        raise
    else:
        session.commit()
        return True
